package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyYiYouHua;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeYiYouHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 易优花 https://console-docs.apipost.cn/preview/8247cc2980e86a26/43ab0daf39f3f761
 * 密码：808909
 * @author 李源聪
 */
@ApiPlan(productId = "30", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatYiYouHuaPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    public static final String KEY = "81A02434530B630D13D751D0202184E7";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        ApiPlatDataExchangeYiYouHua apiPlatDataExchangeYiYouHua = new ApiPlatDataExchangeYiYouHua();
        //  公积金：六个月以上|六个月以下|无
        String accumulation = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", "无")
                .when(apiDataExchangeParameter.getProvidentFund(), "2", "六个月以下")
                .when(apiDataExchangeParameter.getProvidentFund(), "3", "六个月以上")
                .when(apiDataExchangeParameter.getProvidentFund(), "4", "六个月以上")
                .end("无");
        apiPlatDataExchangeYiYouHua.setAccumulation(accumulation);
        // 年龄
        apiPlatDataExchangeYiYouHua.setAge(apiDataExchangeParameter.getAge());
        // 车辆情况
        String carChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", "无")
                .when(apiDataExchangeParameter.getCarInfo(), "2", "有")
                .when(apiDataExchangeParameter.getCarInfo(), "3", "有")
                .when(apiDataExchangeParameter.getCarInfo(), "4", "有")
                .end("无");
        apiPlatDataExchangeYiYouHua.setCar(carChoose);
        // 城市名称
        apiPlatDataExchangeYiYouHua.setCityName(apiDataExchangeParameter.getCity().replaceAll("市", ""));
        // 信用卡额度
        String creditCardChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", "无")
                .when(apiDataExchangeParameter.getCreditLimit(), "2", "10000元以下")
                .when(apiDataExchangeParameter.getCreditLimit(), "3", "10000元以下")
                .when(apiDataExchangeParameter.getCreditLimit(), "4", "10000元以下")
                .when(apiDataExchangeParameter.getCreditLimit(), "5", "30000元以上")
                .when(apiDataExchangeParameter.getCreditLimit(), "6", "10000元以下")
                .end("无");
        apiPlatDataExchangeYiYouHua.setCreditCard(creditCardChoose);
        // 房产情况
        String houseChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", "无")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", "有")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", "有")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", "有")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", "有")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", "有")
                .end("无");
        apiPlatDataExchangeYiYouHua.setHouse(houseChoose);
        // 花呗额度
        String huabeiChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getHbLimit(), "1", "无")
                .when(apiDataExchangeParameter.getHbLimit(), "3", "5000元以下")
                .when(apiDataExchangeParameter.getHbLimit(), "3", "5000-10000元")
                .when(apiDataExchangeParameter.getHbLimit(), "4", "10000元以上")
                .when(apiDataExchangeParameter.getHbLimit(), "5", "10000元以上")
                .end("无");
        apiPlatDataExchangeYiYouHua.setHuabei(huabeiChoose);
        // 保险缴纳年限
        String insuranceChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", "无")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", "2年以下")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", "2年以下")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", "2年以上")
                .end("无");
        apiPlatDataExchangeYiYouHua.setInsurance(insuranceChoose);
        // 贷款金额
        String loanAmountChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", "5万")
                .when(apiDataExchangeParameter.getLoanAmount(), "2", "10万")
                .when(apiDataExchangeParameter.getLoanAmount(), "3", "20万")
                .when(apiDataExchangeParameter.getLoanAmount(), "4", "20万")
                .end("5万");
        apiPlatDataExchangeYiYouHua.setLoanAmount(loanAmountChoose);
        // 芝麻分
        String newSesameSeedChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "4", "700分以上")
                .when(apiDataExchangeParameter.getSesameCredit(), "3", "650-699分")
                .when(apiDataExchangeParameter.getSesameCredit(), "2", "600-649分")
                .when(apiDataExchangeParameter.getSesameCredit(), "1", "600分以下")
                .end("600分以下");
        apiPlatDataExchangeYiYouHua.setNewSesameSeed(newSesameSeedChoose);
        // 职业类型
        String occupationChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "4", "公务员/国企")
                .when(apiDataExchangeParameter.getCareer(), "3", "私营企业主")
                .when(apiDataExchangeParameter.getCareer(), "1", "上班族")
                .when(apiDataExchangeParameter.getCareer(), "2", "自由职业")
                .when(apiDataExchangeParameter.getCareer(), "5", "自由职业")
                .end("自由职业");
        apiPlatDataExchangeYiYouHua.setOccupation(occupationChoose);
        // 逾期情况
        String overdueSituationChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", "无逾期")
                .when(apiDataExchangeParameter.getOverdue(), "2", "当前有逾期")
                .when(apiDataExchangeParameter.getOverdue(), "3", "无逾期")
                .end("无逾期");
        apiPlatDataExchangeYiYouHua.setOverdueSituation(overdueSituationChoose);
        // 省份名称
        String provinceName = apiDataExchangeParameter.getProvinceName().replaceAll("省", "");
        apiPlatDataExchangeYiYouHua.setProvinceName(provinceName);
        // 性别
        String sexChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", "1")
                .when(apiDataExchangeParameter.getSex(), "1", "2")
                .end("1");
        apiPlatDataExchangeYiYouHua.setSex(sexChoose);
        // 社保缴纳情况
        String socialSecurityChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", "无")
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", "六个月以下")
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", "六个月以上")
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", "六个月以上")
                .end("无");
        apiPlatDataExchangeYiYouHua.setSocialSecurity(socialSecurityChoose);
        // 用户IP地址
        if(ValidParam.isEmpty(apiDataExchangeParameter.getIp())){
            apiPlatDataExchangeYiYouHua.setUserIp("127.0.0.1");
        }else {
            apiPlatDataExchangeYiYouHua.setUserIp(apiDataExchangeParameter.getIp());
        }
        // 用户姓名
        apiPlatDataExchangeYiYouHua.setUserName("默认名称");
        // 加密后的用户手机号（MD5）
        apiPlatDataExchangeYiYouHua.setUserPhone(apiDataExchangeParameter.getPhoneMd5());
        // 白条额度
        String whiteStripeChoose = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "5", "10000元以上")
                .when(apiDataExchangeParameter.getBtLimit(), "4", "10000元以上")
                .when(apiDataExchangeParameter.getBtLimit(), "3", "5000-10000元")
                .when(apiDataExchangeParameter.getBtLimit(), "2", "5000元以下")
                .when(apiDataExchangeParameter.getBtLimit(), "1", "无")
                .end("无");
        apiPlatDataExchangeYiYouHua.setWhiteStripe(whiteStripeChoose);
        String signKey = KEY.substring(16);
        String dataKey = KEY.substring(0, 16);
        String reqJson = JsonUtils.toJson(apiPlatDataExchangeYiYouHua);
        String sign = DigestUtils.sha1Hex(reqJson + signKey);
        String encode = EncryptionAndDecryption.encode(EncryptionAndDecryption.encode(reqJson, dataKey));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("systemCode", "GArD");
            newMap.put("action", "authMatch");
            newMap.put("requestId","TD-" + IdUtils.generateIdStr());
            newMap.put("signData", sign);
            newMap.put("encryptData", encode);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        ApiPlatApplyYiYouHua apiPlatApplyYiYouHua = new ApiPlatApplyYiYouHua();
        //  公积金
        String accumulation = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", "无")
                .when(apiApplyParameter.getProvidentFund(), "2", "六个月以下")
                .when(apiApplyParameter.getProvidentFund(), "3", "六个月以上")
                .when(apiApplyParameter.getProvidentFund(), "4", "六个月以上")
                .end("无");
        apiPlatApplyYiYouHua.setAccumulation(accumulation);
        // 年龄
        apiPlatApplyYiYouHua.setBusinessFlowId(apiApplyParameter.dataExchangeApplyId());
        // 业务流水号
        apiPlatApplyYiYouHua.setAge(apiApplyParameter.getAge());
        // 车辆情况
        String carChoose = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", "无")
                .when(apiApplyParameter.getCarInfo(), "2", "有")
                .when(apiApplyParameter.getCarInfo(), "3", "有")
                .when(apiApplyParameter.getCarInfo(), "4", "有")
                .end("无");
        apiPlatApplyYiYouHua.setCar(carChoose);
        // 城市名称
        apiPlatApplyYiYouHua.setCityName(apiApplyParameter.getCity().replaceAll("市", ""));
        // 信用卡额度
        String creditCardChoose = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", "无")
                .when(apiApplyParameter.getCreditLimit(), "2", "10000元以下")
                .when(apiApplyParameter.getCreditLimit(), "3", "10000元以下")
                .when(apiApplyParameter.getCreditLimit(), "4", "10000元以下")
                .when(apiApplyParameter.getCreditLimit(), "5", "30000元以上")
                .when(apiApplyParameter.getCreditLimit(), "6", "10000元以下")
                .end("无");
        apiPlatApplyYiYouHua.setCreditCard(creditCardChoose);
        // 房产情况
        String houseChoose = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", "无")
                .when(apiApplyParameter.getRealEstateInfo(), "2", "有")
                .when(apiApplyParameter.getRealEstateInfo(), "3", "有")
                .when(apiApplyParameter.getRealEstateInfo(), "4", "有")
                .when(apiApplyParameter.getRealEstateInfo(), "5", "有")
                .when(apiApplyParameter.getRealEstateInfo(), "6", "有")
                .end("无");
        apiPlatApplyYiYouHua.setHouse(houseChoose);
        // 花呗额度
        String huabeiChoose = ChooseEq.create()
                .when(apiApplyParameter.getHbLimit(), "1", "无")
                .when(apiApplyParameter.getHbLimit(), "3", "5000元以下")
                .when(apiApplyParameter.getHbLimit(), "3", "5000-10000元")
                .when(apiApplyParameter.getHbLimit(), "4", "10000元以上")
                .when(apiApplyParameter.getHbLimit(), "5", "10000元以上")
                .end("无");
        apiPlatApplyYiYouHua.setHuabei(huabeiChoose);
        // 保险缴纳情况
        String insuranceChoose = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", "无")
                .when(apiApplyParameter.getInsurancePolicy(), "2", "2年以下")
                .when(apiApplyParameter.getInsurancePolicy(), "3", "2年以下")
                .when(apiApplyParameter.getInsurancePolicy(), "4", "2年以上")
                .end("无");
        apiPlatApplyYiYouHua.setInsurance(insuranceChoose);
        // 贷款金额
        String loanAmountChoose = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", "5万")
                .when(apiApplyParameter.getLoanAmount(), "2", "10万")
                .when(apiApplyParameter.getLoanAmount(), "3", "20万")
                .when(apiApplyParameter.getLoanAmount(), "4", "20万")
                .end("5万");
        apiPlatApplyYiYouHua.setLoanAmount(loanAmountChoose);
        // 芝麻分
        String newSesameSeedChoose = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "4", "700分以上")
                .when(apiApplyParameter.getSesameCredit(), "3", "650-699分")
                .when(apiApplyParameter.getSesameCredit(), "2", "600-649分")
                .when(apiApplyParameter.getSesameCredit(), "1", "600分以下")
                .end("600分以下");
        apiPlatApplyYiYouHua.setNewSesameSeed(newSesameSeedChoose);
        // 职业类型
        String occupationChoose = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "4", "公务员/国企")
                .when(apiApplyParameter.getCareer(), "3", "私营企业主")
                .when(apiApplyParameter.getCareer(), "1", "上班族")
                .when(apiApplyParameter.getCareer(), "2", "自由职业")
                .when(apiApplyParameter.getCareer(), "5", "自由职业")
                .end("自由职业");
        apiPlatApplyYiYouHua.setOccupation(occupationChoose);
        // 逾期情况
        String overdueSituationChoose = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", "无逾期")
                .when(apiApplyParameter.getOverdue(), "2", "当前有逾期")
                .when(apiApplyParameter.getOverdue(), "3", "无逾期")
                .end("无逾期");
        apiPlatApplyYiYouHua.setOverdueSituation(overdueSituationChoose);
        // 省份名称
        String provinceName = apiApplyParameter.getProvinceName();
        apiPlatApplyYiYouHua.setProvinceName(provinceName);
        // 性别
        String sexChoose = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", "1")
                .when(apiApplyParameter.getSex(), "1", "2")
                .end("1");
        apiPlatApplyYiYouHua.setSex(sexChoose);
        // 社保缴纳情况
        String socialSecurityChoose = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", "无")
                .when(apiApplyParameter.getSocialSecurity(), "2", "六个月以下")
                .when(apiApplyParameter.getSocialSecurity(), "3", "六个月以上")
                .when(apiApplyParameter.getSocialSecurity(), "4", "六个月以上")
                .end("无");
        apiPlatApplyYiYouHua.setSocialSecurity(socialSecurityChoose);
        // 用户IP地址
        if(ValidParam.isEmpty(apiApplyParameter.getIp())){
            apiPlatApplyYiYouHua.setUserIp("127.0.0.1");
        }else {
            apiPlatApplyYiYouHua.setUserIp(apiApplyParameter.getIp());
        }
        // 用户姓名
        apiPlatApplyYiYouHua.setUserName(apiApplyParameter.getUserName());
        // 用户手机号
        apiPlatApplyYiYouHua.setUserPhone(apiApplyParameter.getPhone());
        // 白条额度
        String whiteStripeChoose = ChooseEq.create()
                .when(apiApplyParameter.getBtLimit(), "5", "10000元以上")
                .when(apiApplyParameter.getBtLimit(), "4", "10000元以上")
                .when(apiApplyParameter.getBtLimit(), "3", "5000-10000元")
                .when(apiApplyParameter.getBtLimit(), "2", "5000元以下")
                .when(apiApplyParameter.getBtLimit(), "1", "无")
                .end("无");
        apiPlatApplyYiYouHua.setWhiteStripe(whiteStripeChoose);

        String signKey = KEY.substring(16);
        String dataKey = KEY.substring(0, 16);
        String reqJson = JsonUtils.toJson(apiPlatApplyYiYouHua);
        String sign = DigestUtils.sha1Hex(reqJson + signKey);
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("systemCode", "GArD");
            newMap.put("action", "authPush");
            newMap.put("requestId", "TD-" + IdUtils.generateIdStr());
            newMap.put("signData", sign);
            newMap.put("encryptData", EncryptionAndDecryption.encode(EncryptionAndDecryption.encode(reqJson,dataKey)));

        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        JSONObject decode = EncryptionAndDecryption.decode(jsonObject, KEY, true);
        JSONObject result = JsonUtils.get(decode.getString("result"));
        if (result == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        String resultCode = result.getString("resultCode");
        if (!Eq.object(resultCode, "000000")) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject decode = EncryptionAndDecryption.decode(jsonObject, KEY, true);
        JSONObject result = null;
        if (decode != null) {
            result = JsonUtils.get(decode.getString("result"));
        }else {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        String resultCode = result.getString("resultCode");
        if (!Eq.object(resultCode, "000000")) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = JsonUtils.get(decode.getString("result"));

        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("exhibitionName");
        String logo = resData.getString("logo");
        String orderId = resData.getString("businessFlowId");
        String callUrl = resData.getString("jumpUrl");

        RespPlatformPhoneMd5DataExchange respPlatformPhoneMd5DataExchange = RespPlatformPhoneMd5DataExchange.ofSuc();

        respPlatformPhoneMd5DataExchange.setPrice(price);
        respPlatformPhoneMd5DataExchange.setLogoPath(logo);
        respPlatformPhoneMd5DataExchange.setDisplayName(companyName);
        respPlatformPhoneMd5DataExchange.setProductName(productName);
        respPlatformPhoneMd5DataExchange.setApplyId(orderId);
        respPlatformPhoneMd5DataExchange.setCallUrl(callUrl);

        return respPlatformPhoneMd5DataExchange;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String businessFlowId = jsonObject.getString("businessFlowId");

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setApplyId(businessFlowId);
        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        boolean b = apiBizStatus.hasBizSuc();

        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", "200");
                newHashMap.put("msg", apiBizStatus.getBizMsg());
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", "500");
            newHashMap.put("msg", apiBizStatus.getBizMsg());
        });
    }

    private static class EncryptionAndDecryption {

        private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

        private static final String KEY_ALGORITHM = "AES";

        private static byte[] getUTF8Bytes(String input) {
            return input.getBytes(StandardCharsets.UTF_8);
        }
        /**
         * 解密报文
         * @param map 返回参数
         * @param key 密钥
         */
        private static JSONObject decode(Map<String, String> map, String key){
            String signKey = key.substring(16);
            String dataKey = key.substring(0, 16);
            String result = decode(decode(map.get("encryptData")), dataKey);
            String signature = map.get("signData");
            String reSign = DigestUtils.sha1Hex(result + signKey);
            if (signature != null && signature.equals(reSign)) {
                return JSONObject.parseObject(result);
            }
            return null;
        }

        /**
         * 解密报文
         * @param map 返回参数
         * @param key 密钥
         * @param isSynchronize 是否同步通知
         */
        public static JSONObject decode(JSONObject map, String key, boolean isSynchronize){
            String signKey = key.substring(16);
            String dataKey = key.substring(0, 16);
            String result = decode(decode(map.getString("encryptData")), dataKey);
            String signature = map.getString("signature");
            String reSign = "";
            if (isSynchronize){
                reSign = DigestUtils.sha1Hex(result + signKey);
            } else {
                reSign = DigestUtils.sha1Hex(map.get("encryptData") + signKey);
            }
            if (signature != null && signature.equals(reSign)) {
                return JSONObject.parseObject(result);
            }
            return null;
        }

        /**
         * 加密报文
         */
        private static Map<String, String> encryption(String key, String dataJson, String partnerNo, String orderId, String action) {
            Map<String, String> params = new HashMap<>(5);
            try {
                String signKey = key.substring(16);
                String dataKey = key.substring(0, 16);
                String sign = DigestUtils.sha1Hex(dataJson + signKey);
                params.put("encryptData", encode(encode(dataJson, dataKey)));
                params.put("signData", sign);
                params.put("orderId", orderId);
                params.put("partnerNo", partnerNo);
                params.put("action", action);
            } catch (Exception e) {

            }
            return params;
        }

        /**
         * 使用Base64解密算法解密字符串
         */
        private static byte [] decode(String encodeStr) {
            byte[] b = encodeStr.getBytes(StandardCharsets.UTF_8);
            Base64 base64 = new Base64();
            return base64.decode(b);
        }

        /**
         * 使用Base64加密算法加密字符串
         */
        public static String encode(byte[] plainBytes) {
            Base64 base64 = new Base64();
            plainBytes = base64.encode(plainBytes);
            return new String(plainBytes, StandardCharsets.UTF_8);
        }

        /**
         * 解密
         */
        private static String decode(byte[] encodeStr, String keyText) {
            return AESDecrypt(encodeStr,keyText);
        }

        @Deprecated
        private static String  AESDecrypt(byte[] encodeStr, String keyText) {
            byte[] bytes = AESDecrypt(encodeStr, getUTF8Bytes(keyText), KEY_ALGORITHM, CIPHER_ALGORITHM,
                    keyText);
            return new String(bytes, StandardCharsets.UTF_8);
        }

        /**
         * AES解密
         *
         * @param encryptedBytes
         *            密文字节数组，不经base64编码
         * @param keyBytes
         *            密钥字节数组
         * @param keyAlgorithm
         *            密钥算法
         * @param cipherAlgorithm
         *            加解密算法
         * @param IV
         *            随机向量
         * @return 解密后字节数组
         */
        @Deprecated
        private static byte[] AESDecrypt(byte[] encryptedBytes, byte[] keyBytes, String keyAlgorithm,
                                         String cipherAlgorithm, String IV) {
            try {
                if (keyBytes.length % 8 != 0 || keyBytes.length < 16 || keyBytes.length > 32) {
                    throw new RuntimeException("AES密钥长度不合法");
                }
                Cipher cipher = Cipher.getInstance(cipherAlgorithm);
                SecretKey secretKey = new SecretKeySpec(keyBytes, keyAlgorithm);
                if (IV != null) {
                    IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
                    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
                } else {
                    cipher.init(Cipher.DECRYPT_MODE, secretKey);
                }
                return cipher.doFinal(encryptedBytes);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(String.format("没有[%s]此类加密算法", cipherAlgorithm),e);
            } catch (NoSuchPaddingException e) {
                throw new RuntimeException(String.format("没有[%s]此类填充模式", cipherAlgorithm),e);
            } catch (InvalidKeyException e) {
                throw new RuntimeException("无效密钥",e);
            } catch (InvalidAlgorithmParameterException e) {
                throw new RuntimeException("无效密钥参数",e);
            } catch (BadPaddingException e) {
                throw new RuntimeException("错误填充模式",e);
            } catch (IllegalBlockSizeException e) {
                throw new RuntimeException("解密块大小不合法",e);
            }
        }

        /**
         * AES 加密
         *
         */
        public static byte[] encode(String plainText, String keyText){
            try {
                return AESEncrypt(plainText, keyText);
            } catch (Exception e){

            }
            return null;
        }

        @Deprecated
        private static byte[] AESEncrypt(String plainText, String keyText) throws Exception {
            return AESEncrypt(getUTF8Bytes(plainText), getUTF8Bytes(keyText), KEY_ALGORITHM, CIPHER_ALGORITHM,
                    keyText);
        }

        /**
         * AES解密
         *
         * @param plainBytes      密文字节数组，不经base64编码
         * @param keyBytes        密钥字节数组
         * @param keyAlgorithm    密钥算法
         * @param cipherAlgorithm 加解密算法
         * @param IV              随机向量
         * @return 解密后字节数组
         */
        @Deprecated
        private static byte[] AESEncrypt(byte[] plainBytes, byte[] keyBytes, String keyAlgorithm, String cipherAlgorithm,
                                         String IV) {
            try {
                if (keyBytes.length % 8 != 0 || keyBytes.length < 16 || keyBytes.length > 32) {
                    throw new RuntimeException("AES密钥长度不合法");
                }
                Cipher cipher = Cipher.getInstance(cipherAlgorithm);
                SecretKey secretKey = new SecretKeySpec(keyBytes, keyAlgorithm);
                if (null != IV) {
                    IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
                    cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
                } else {
                    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                }
                return cipher.doFinal(plainBytes);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(String.format("没有[%s]此类加密算法", cipherAlgorithm),e);
            } catch (NoSuchPaddingException e) {
                throw new RuntimeException(String.format("没有[%s]此类填充模式", cipherAlgorithm),e);
            } catch (InvalidKeyException e) {
                throw new RuntimeException("无效密钥",e);
            } catch (InvalidAlgorithmParameterException e) {
                throw new RuntimeException("无效密钥参数",e);
            } catch (BadPaddingException e) {
                throw new RuntimeException("错误填充模式",e);
            } catch (IllegalBlockSizeException e) {
                throw new RuntimeException("加密块大小不合法",e);
            }
        }
    }
}
